<template>
  <span>
    <!-- 右键菜单 -->
    <!-- <contextMenuComp :contextMenuBts="contextMenuBts" :contextMenuDomId="contextMenuDomId"></contextMenuComp> -->

    <!-- 弹出对话框  -->
    <div id="topo-bus-contextMenu-dialog" style="display:none">
      <component :is="currentViewComp" :currentMapElementData="currentMapElementData" transition="fade" transition-mode="out-in" keep-alive :scriptResult="scriptResult" @transferCloseDialog="transferCloseDialog" @transferCheckedNodes="transferCheckedNodes" @transferModifiedNode="transferModifiedNode"></component>
    </div>

    <!-- 右侧弹出窗口 -->
    <addDevice :devId='dataId' :devType="dataType" :devName="dataName"></addDevice>
  </span>
</template>
<script>
import eventHubs from 'common/eventHubs'
import resType from 'common/resTypeEnum'
import { TOPO_TYPE_BUS } from 'common/resTypeEnum'
import art from 'utils/artdialog'
import topoApi from 'api/topo'
import iconApi from 'api/config/iconmanager'

var dialog = require('artDialog')

import btnEvent from 'common/topo/btnEvent'

// import contextMenuComp from 'components/topo/contextMenu.vue'
import modifyhostComp from 'views/topo/modifyHostInfo.vue'
import modifyLinkComp from 'views/topo/modifyLink.vue'
import exchangeRuijieComp from 'views/topo/exchange_ruijie.vue'
import scriptResultComp from 'views/topo/scriptResult.vue'
import deviceTreeComp from 'views/device/deviceTree.vue'
import addDevice from 'views/device/addDevice.vue'

import cxmenu from 'common/topo/topoMenu.js'
import {createNode} from 'common/topo/addTopoElement.js'

export default {
  data() {
    return {
      graphView: null,
      // contextMenuDomId: '',
      // contextMenuBts: [],
      // contextMenuNodeBts: [],
      // contextMenuLinkBts: [],
      // contextMenuBusBts: [],
      currentViewComp: null,
      scriptResult: '',
      currentMapElementData: {},
      currentNodeOrLink: null,
      imageAndHostidMap: {},
      importDeviceDialog: null,
      modifyhostDialog: null,
      mouseupEventPos: {
        x: 100,
        y: 100
      },
      dataId: '',
      dataType: 2,
      dataName: ''
    }
  },
  created() {
    const self = this;
    eventHubs.getEventHub().$on('topoGraphView', (topoGraphView) => {
      self.graphView = topoGraphView;
      self.initContextMenu();
    });
  },
  mounted() {
    this.initImageAndHostidMap();
  },
  components: {
    // contextMenuComp,
    modifyhostComp,
    modifyLinkComp,
    exchangeRuijieComp,
    scriptResultComp,
    deviceTreeComp,
    addDevice
  },
  methods: {
    initImageAndHostidMap() {
      const self = this;
      iconApi.getImageAndHostid().then(response => {
        self.imageAndHostidMap = response.data;
      });
    },
    initContextMenu() {
      const self = this;
      let menu = cxmenu
      //设置菜单动作action
      //查看主机性能
      menu.performanceMenu.action = function(item, e) {
        console.log('查看主机性能')
        self.getEleData(self, e)
        if (self.currentMapElementData) {
          self.dataId = self.currentMapElementData.elementid;
          self.dataName = self.currentMapElementData.label;
          $(".rightLayout").show().animate({
            left: "20%"
          }).addClass("showBlock");
          $(".layoutTop").show().animate({
            left: "20%"
          }); //右侧顶部固定
          $("body").addClass("hideScoll");
        }
      }
      //修改设备信息
      menu.editDeviceMenu.action = function(item, e) {
        console.log('修改设备信息')
        self.getEleData(self, e)
        if (self.currentMapElementData) {
          self.currentViewComp = modifyhostComp;
          self.modifyhostDialog = art.artdialog(self.$t('Modify Host Infomation'), $('#topo-bus-contextMenu-dialog'), 600, 400, 'topodialog');
          self.$store.dispatch('setCurMapElement', self.currentMapElementData);
        }
      }
      //导入设备
      menu.importDeviceMenu.action = function(item, e) {
        self.currentViewComp = deviceTreeComp;
        self.importDeviceDialog = art.artdialog(self.$t('Import Device'), $('#topo-bus-contextMenu-dialog'), 400, 500, 'topodialog');
      }
      //新增连接
      menu.addLinkMenu.action = function(item, e) {
        console.log('新增连接')
        const sysmapid = self.$store.state.topo.sysmapid;
        const message = { success: self.$t('Created Successfully'), failed: self.$t('Failed to create') };
        btnEvent.topoAddLink(self.graphView, sysmapid, message);
      }
      //删除拓扑图元素
      menu.delEleMenu.action = function(item, e) {
        console.log('删除')
        const message = { success: self.$t('Deleted Successfully'), failed: self.$t('Failed to delete'), info: self.$t('Cancel to delete') };
        btnEvent.deleteMapElement(self.graphView, message);
      }
      // 查看子拓扑
      menu.subtopoMenu.action = function(item, e) {
        console.log('查看子拓扑')
        self.getEleData(self, e)
        if (self.currentMapElementData) {
          const routerStr = '/bus/topo';
          const sysmapid = self.currentMapElementData.elementid;
          self.$router.push({ path: routerStr, query: { sysmapid: sysmapid } });
          eventHubs.getEventHub().$emit("sysmapidChange", sysmapid);
          self.$store.dispatch('setCurSysmapid', sysmapid);
        }
      }
      // 初始化右键菜单
      menu.init(TOPO_TYPE_BUS, self.graphView,self)
    },
    //获取鼠标点击时的元素数据
    getEleData(self, e) {
      let eles = self.graphView.getDataModel().getSelectionModel().getSelection()
      if (eles != null && eles.length == 1) {
        self.currentNodeOrLink = eles.get(0);
        if (self.currentNodeOrLink) {
          const nodeOrLink = self.currentNodeOrLink._attrObject;
          let nodeOrLinkData = null;
          if (nodeOrLink != undefined && nodeOrLink != null) {
            nodeOrLinkData = nodeOrLink.data;
            nodeOrLinkData.elementtypeName = self.getElementNameByType(nodeOrLinkData.elementtype);
            self.currentMapElementData = nodeOrLinkData;
          }
        } else {
          self.currentNodeOrLink = null
        }
      }
    }
    ,
    getElementNameByType(elementtype) {
      return resType.getElementNameByType(elementtype);
    },
    isObjBlank(obj) {
      return (obj === null) || (obj === undefined) || (obj === '');
    },
    closeDialog() {
      if (this.importDeviceDialog != null) {
        this.importDeviceDialog.close();
      }
      if (this.modifyhostDialog != null) {
        this.modifyhostDialog.close();
      }
    },
    transferCloseDialog(msg) {
      this.closeDialog();
      this.$message(msg);
    },
    transferCheckedNodes(checkedNodes) {
      const self = this;
      let selements = [];
      const sysmapid = this.$store.state.topo.sysmapid;
      const dataModel = this.graphView.getDataModel();

      // api添加记录
      $.each(checkedNodes, function() {
        const etype = this.type;
        if (etype == 2) {
          let element = {};
          element.label = this.host;
          element.elementid = this.id;
          element.sysmapid = sysmapid;
          element.elementtype = "0";
          const sysimage = self.imageAndHostidMap[this.hostid];
          if (!self.isObjBlank(sysimage)) {
            element.iconid_off = sysimage.imageid;
          } else {
            element.iconid_off = "150";
          }
          element.x = self.mouseupEventPos.x;
          element.y = self.mouseupEventPos.y;
          selements.push(element);
        }
      });
      //使用过滤函数过滤数组元素 过滤函数必须返回 true 以保留元素或 false 以删除元素。
      let result = $.grep(selements, function(ele){
          let flag = true
          dataModel.each(function(node,index){
            let data = node.getAttr('data')
            if(ele.elementid == data.elementid){
              flag = false
              return
            }
          })
          return flag
      });
      if(result.length == 0){
          self.$message('拓扑图中已存在选中元素！');
          self.closeDialog();
          return
      }
      topoApi.createMapElement(result).then(response => {
        if (response.status == 200) {
          const elementData = response.data;
          $.each(elementData, function() {
            // 创建图形元素
            var newNode = createNode(this, self.sysIcons,self.defaultNodeImg)
            dataModel.add(newNode);
          });
          self.layout(); // 重新自动布局
          self.closeDialog();
          self.$message(self.$t('Created Successfully'));
        }
      }).catch(err => {
        self.$message.error(self.$t('Failed to create'));
      });
    },
    transferModifiedNode(transferData) {
      const modifiedNode = transferData.modifiedNode;
      const newIcon = transferData.newIcon;

      const dataModel = this.graphView.getDataModel();
      const data = dataModel.getDataById(modifiedNode.selementid);
      data.setImage('data:image/png;base64,' + newIcon.image);
      this.closeDialog();
    },
    layout() {
      const self = this;
      // 布局设置
      const autoLayout = new ht.layout.AutoLayout(this.graphView);
      // this.autoLayout.setAnimate(animate);
      autoLayout.layout('symmetric', function() {
        self.graphView.fitContent(true);
      });
    }
  },
  computed: {
    sysIcons() {
      return this.$store.state.topo.sysIcons;
    },
    defaultNodeImg(){
      return this.$store.state.topo.defaultNodeImg;
    }
  }
}
</script>
